package MobileCommServer;

public class SerialPacket {
	public static final int STX = 2;
	public static final int ETX = 2;
	public static final int SIZE = 4;
	public static final int KEY = 4;
	
	public static byte[] MakeSerialPacket(byte[] data, int hashCode) {
		int dataSize = data.length;
		int bufSize = STX + SIZE + KEY + dataSize + ETX;

		byte[] sendBuf = new byte[bufSize];

		int idx = 0;
		byte[] stx = { (byte) 0x01, (byte) 0x01 };
		byte[] etx = { (byte) 0x02, (byte) 0x02 };
		byte[] size = ByteUtil.toBytes(dataSize);
		byte[] key = ByteUtil.toBytes(hashCode);
		
		System.arraycopy(stx, 0, sendBuf, idx, STX);			idx += STX;
		System.arraycopy(size, 0, sendBuf, idx, SIZE);			idx += SIZE;
		System.arraycopy(key, 0, sendBuf, idx, KEY);			idx += KEY;
		System.arraycopy(data, 0, sendBuf, idx, dataSize);		idx += dataSize; 
		System.arraycopy(etx, 0, sendBuf, idx, ETX);
		
		return sendBuf;
	}
	
	public static byte[] GetDataPart(byte[] data, int[] nKey) {
		int idx = 0;

		byte[] stx = new byte[STX];
		byte[] size = new byte[SIZE];
		byte[] key = new byte[KEY];
		byte[] etx = new byte[ETX];

		System.arraycopy(data, idx, stx, 0, STX);		idx += STX;
		System.arraycopy(data, idx, size, 0, SIZE);		idx += SIZE;
		System.arraycopy(data, idx, key, 0, KEY);		idx += KEY;
		nKey[0] = ByteUtil.toInt(key);
		
		int dataSize = ByteUtil.toInt(size);
		byte[] dataPart = new byte[dataSize];

		System.arraycopy(data, idx, dataPart, 0, dataSize);		idx += dataSize;
		System.arraycopy(data, idx, etx, 0, ETX);
		
		return dataPart;
	}
	
	public static String ConvertByteArrToStr(byte[] data) {
		return new String(data, 0, data.length);
	}
}
